package daily;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ThreeConditionThreadCommunication {
	
	private void init(){
		final Business business=new Business();
		new Thread(new Runnable(){

			@Override
			public void run() {
				for(int i=0;i<50;i++){
					business.doSub2(i);
				}
				
			}
			
		}).start();
		
		new Thread(new Runnable(){

			@Override
			public void run() {
				for(int i=0;i<50;i++){
					business.doSub3(i);
				}
				
			}
			
		}).start();
		for(int i=0;i<50;i++){
			business.doMain(i);
		}
	}

	public static void main(String[] args) {
		ThreeConditionThreadCommunication ttc=new ThreeConditionThreadCommunication();
		ttc.init();
	}
	
	
	class Business{
		private volatile int squ=1;

		private Lock lock=new ReentrantLock();
		private Condition notMain=lock.newCondition();
		private Condition notSub2=lock.newCondition();
		private Condition notSub3=lock.newCondition();
		public  void doSub2(int count){
			lock.lock();
			try {
				while(!(squ==2)){
					try {
						notSub2.await();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				
				for(int i=0;i<5;i++){
					System.out.println(count+" loop "+ i+"    doSub2--------");
				}
				squ=3;
				notSub3.signal();
			}finally{
				lock.unlock();
			}
			
		}
		
		public  void doSub3(int count){
			lock.lock();
			try {
				while(!(squ==3)){
					try {
						notSub3.await();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				
				for(int i=0;i<7;i++){
					System.out.println(count+" loop "+ i+"    doSub3--------");
				}
				squ=1;
				notMain.signal();
			}finally{
				lock.unlock();
			}
			
		}
		public  void doMain(int count){
			lock.lock();
			try {
				while(!(squ==1)){
					try {
						notMain.await();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				
				for(int i=0;i<10;i++){
					System.out.println(count+" loop "+ i+"    doMain--------");
				}
				squ=2;
				notSub2.signal();
			} finally{
				lock.unlock();
			}
		}
	}
}
